Q: How can i make my caroutine run in every x seconds I created a caroutine, and i want it to run in every x seconds. i tried using while loop but it didn't worked for this caroutine. can anybody please help ? thanks.
 IEnumerator StartFire()
{

    {
        Firing = true;

        animator.SetBool("isFiring", true);

        yield return new WaitForSeconds(2);

        Firing = false;

        animator.SetBool("isFiring", false);

    }

}

A: I think you would be better off using InvokeRepeating(string methodName, float time, float repeatRate). You only need to call it once and it will repeat.
Example:
void Start()
{
    InvokeRepeating("myTask", 1.5f, 1.5f);
}

void myTask()
{
    // Execute repetitive task.
}

If you want to stop it at any point you simply have to call: CancelInvoke(string methodName);.
Example:
void Update()
{
    if (Input.GetKeyDown(KeyCode.S))
        CancelInvoke();
}

This would put an end to the repetitive task.


Q: Where can I place external JAR references of a WAR file other than WEB-INF/lib or WL_HOME/server/lib I have 120 Java Projects exported as JAR files in D:/FC/APP_LIB folder. Now I developed a Web Service (JAX-WS), to be deployed on Weblogic 12c (12.1.2), which refers to those JAR files. I don't think it will be a good practice to add all the JARs into the WEB-INF/lib of the WAR file (and it will continue in all subsequent WARs I develop).
Also, I want to avoid those JARs to be kept in WL_HOME/server/lib folder (default reference) as anytime a change is made in any of the Java Projects will require a deployment in WL_HOME/server/lib.
Is there any way I can give an external JAR(s) reference in WAR or Weblogic without embedding them into WAR?

A: You can write (and use) a separate class loader to load classes from anywhere.
That being said I suggest putting the jars into each .war file. Disk space and RAM should not be the problem.

*

*If a central .jar is modified (and a bug is introduced), all web apps will fail.

*You probably test your web app against a specific version of your libraries. If you update a central .jar, you have to re-run the tests for each application.

Generally speaking you will probably run into problems because of dependencies.

A: May you need Create Shared Java EE Library or Optional Package. See more in Install a Java EE library and Understanding WebLogic Server Application Classloading.

A: You can modify the script used to start Weblogic to include the external directory in the server's classpath.  See %DOMAIN_HOME%\bin\setDomainEnv.sh (or .cmd if Windows).


Q: how to write asp.net to create a file in sharepoint? After giving up java script, I'm writing the asp.net to make a popup, and once the user finish wrting the content and title, it will make a .aspx file and upload to documentary library.
But how can I do that? I googled but not many materials on that!
Anyone can help?


Q: Core Data Fetch GrandChild from Parent Thank  you for your help in advance.
I am able to fetch a child entity from a parent, as seen in the code below, but I can not figure out how to fetch the grandchild based on certain on child in a parent.
How do I add on to or change my existing code to get values out of a grandchild based on the child attributes?
    NSMutableArray *createdMutable = [[NSMutableArray alloc]init];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor      alloc]initWithKey:@"randomAttribute" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:2];
    NSMutableArray *sortedResults = [[NSMutableArray alloc] initWithArray:   [parentEntity.parentToChild allObjects]];
    [sortedResults sortUsingDescriptors:sortDescriptors];
    [sortedResults valueForKey:@"randomAttribute"];

    NSString *addedCreatedMutable;
    for (int i = 0; [sortedResults count] > i; i++) {
            addedCreatedMutable =  [[sortedResults valueForKey:@"randomAttribute"]objectAtIndex:i];
            addedCreatedMutable =  [addedCreatedMutable stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

            if ([createdMutable containsObject:addedCreatedMutable]) {

            }else{
                    [createdMutable addObject:addedCreatedMutable];
            }

A: Can you list the objects and their relationship names? What you're asking is of course possible, but it's a bit hard to grok (for me) from what's above. A couple of suggestions without that;

*

*You can traverse the relationship from parent to children (not sure if child is a to-many or a to-one though) and again out to the grandchild

*You can get funkier using a SUBQUERY() NSPredicate. Advantage is fetch speed, disadvantage is that it's a bit more complex (and sometimes can indicate that you're going about things in not the best way).


Q: How can I pass an array through a Helm template? I'm using Helm v3.
The issue is that I've a template which gets an input value from a values.yaml file.
I've a parameter that looks as follows:
{{ if .Values.school.students}}
students: {{ .Values.school.students}}
{{ end }}

Now, the actual value of students looks something like this:
students: ["student1", "student2", "student3"]

I need students to be an array but currently it gets passed as a string.
I read a few answers online where it was mentioned that we can use "--set" flag but I'm not clear.
Does anyone know how to fix this?

A: You can loop through .Values.school.students using range
{{- if .Values.school.students }}
  students: -|
  {{- range .Values.school.students }}
    - {{ . | quote }}
  {{- end }}
{{- end -}}


Q: Rails and authlogic, Not able to solve dependencies This is my Gemfile:
gem "rails", "~> 2.3.8"
gem "rake", "0.9.2"
gem 'mysql', '2.8.1'

gem 'aasm', '2.1.5'
gem "authlogic", "2.1.6"
gem "acl9", "0.12.0"
gem "formtastic", "1.2.5"

But bundle install reports:
Bundler could not find compatible versions for gem "activesupport":
In Gemfile:
    rails (~> 2.3.8) ruby depends on
      activesupport (= 2.3.8) ruby

    authlogic (= 2.1.6) ruby depends on
      activesupport (1.0.0)

UPDATE
I've tried different combinations of gem versions.
And finally found a row without the version specification... that I didn't saw between comments. So the code snippet above was already correct.

A: Do you really need to use those versions?
Why not simply replace
gem "authlogic", "2.1.6"

with
gem "authlogic"

and let the bundle solve version dependencies?
Sometimes after doing so in the gemfile you get an error from the bundler and you have to run bundle update authlogic before the general bundle install


Q: Testing fragment using FragmentScenario results in java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
I have tried to test my fragment using fragment scenario but I always get the below error

@RunWith(AndroidJUnit4::class)
class HomeFragmentTest {

    @Test
    fun fab() {
        val scenario = launchFragmentInContainer<HomeFragment>()
    }
}.

java.lang.RuntimeException: java.lang.IllegalStateException: Can not
  perform this action after onSaveInstanceState
      at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441)
      at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564)
      at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300)
      at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
      at com.example.myapplication.ui.home.HomeFragmentTest.fab(HomeFragmentTest.kt:31)
      at java.lang.reflect.Method.invoke(Native Method)
      at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
      at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
      at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
      at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
      at org.junit.runners.Suite.runChild(Suite.java:128)
      at org.junit.runners.Suite.runChild(Suite.java:27)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
      at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
      at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
      at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2209)
      Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
      at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1691)
      at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1794)
      at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1814)
      at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:297)
      at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:317)
      at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:301)
      at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:551)
      at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source:4)
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2227)
      at android.os.Handler.handleCallback(Handler.java:883)
      at android.os.Handler.dispatchMessage(Handler.java:100)
      at android.os.Looper.loop(Looper.java:237)
      at android.app.ActivityThread.main(ActivityThread.java:7811)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076)


Q: flex 3 - canvas background visibility issue, how to place bg on top left corner update1 please read the updated para below
update2 created a test app. figured out that the flex tries to place the bg in the center of the container (canvas). so the new question is "how to position bg image to the left top corner when the bg image is smaller than the canvas (parent). but still there is mystical puzzle unsolved which I am thinking is related to how flex places the child. please read update2 at bottom
update3 workaround - not working
I am trying to figure out to fix the issue where the background image of a canvas is not appearing.
I have flex 3.5 app, I have set height and width to 648x1008
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="absolute"
            width="1008" height="648"

in this I have a 3 child canvas components. all of them are added dynamically and positioned to 0,0, two canvas' height, width are set to 100%.
width="100%" height="100%"

my 3rd canvas comp is the main component which is quit larger (4096x4096). i have code to start and stop drag this canvas in mousedown and up handlers
        mouseDown="mouseDownHandler()"
        mouseUp="mouseUpHandler()"
        width="{GameConfig.FULL_GAME_SCREEN_WIDTH}"
        height="{GameConfig.FULL_GAME_SCREEN_HEIGHT}"
        backgroundImage="{GameResource.bg}"

dimensions defined in variables in GameConfig.as
    //game screen dimensions
    public static const FULL_GAME_SCREEN_WIDTH:int = 4096;
    public static const FULL_GAME_SCREEN_HEIGHT:int = 4096;

bg class defined in variable in GameResource.as
    [Embed(source="../../../../assets/images/bg.jpg")]
    public static const bg:Class;

background image path is perfect, I have verified by adding a dummy image to the problem canvas and set the same source ({GameResource.bg})
Now the problem is that the background image is not at all appearing
Other two canvas doesnt have any background color they just have few components (buttons and images) positioned in bottom and top which means the problem canvas is not hidden behind the other canvas. Most importantly the children inside the problem canvas are appearing
I have created a dummy app which is working fine as excpeted
 <?xml version="1.0" encoding="utf-8"?>
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            height="600" width="800" layout="absolute"
            horizontalScrollPolicy="off" verticalScrollPolicy="off">
<mx:Script>
    <![CDATA[
        import com.fg.greenrev.config.GameResource;
    ]]>
</mx:Script>

<mx:Canvas id="bg" horizontalScrollPolicy="off" verticalScrollPolicy="off"
           height="1600" width="4096"
           backgroundColor="0xccbbdd"
           backgroundImage="{GameResource.bg}"
           mouseDown="{bg.startDrag(false,new Rectangle(-3296,-1000,3296,1000))}" mouseUp="{bg.stopDrag()}">
</mx:Canvas>

</mx:Application>

can some one please help me.
Update1:
 I have just modified the code, I turned on scrolling policy of main application and I have removed the bgimage from problem canvas to its child canvas whos size is also same as problem canvas and now bg appears roughly at 2x (1400) of the app screen height and slightly to the right of the screen (around 200px). If move the bgimage to problem canvas it doesnt appear atall again. It seems like the problem with how/where flex adds the bgimage. I was assuming it adds at 0,0 but it looks like its not.
Update2:
I have tried created a dummy app simulating the scenario with dummy code. I narrowed down the issue by changing the FULL_GAME_SCREEN_HEIGHT to the actual size of the bg (1600). Earlier it was larger than the bg (more than 2.5x). Now the image is appearing properly. The issue seems to be with the flex trying to lay the image in the center of the canvas.
I could replicate the issue so that you can try this in your environment and see what is happening
Main App
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            height="600" width="800" layout="absolute"
            creationComplete="init()">
            <!--horizontalScrollPolicy="off" verticalScrollPolicy="off"-->
<mx:Script>
    <![CDATA[
        import _dummy.test1;
        import _dummy.test2;
        import _dummy.test3;

        import com.fg.greenrev.config.GameResource;

        private function init():void{

            var t1:test1 = new test1();
            addChild(t1);

            t1.init();

            var t2:test2 = new test2();
            addChild(t2);

            var t3:test3 = new test3();
            addChild(t3);

        }

    ]]>
</mx:Script>

</mx:Application>

** test1.mxml -  Child component (the problem 1)*

<mx:Script>
    <![CDATA[
        import com.fg.greenrev.config.GameConfig;
        import com.fg.greenrev.config.GameResource;

        import mx.states.AddChild;

        public function init():void{

            var c1:test1Child = new test1Child();
            addChild(c1);
        }
    ]]>
</mx:Script>
<mx:Label x="10" y="10" text="Test1"/>

</mx:Canvas>

* test2.mxml - child2 (no problem) *
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
       horizontalScrollPolicy="off" verticalScrollPolicy="off"
       width="100%" height="100%"
       x="0" y="0">
<mx:Label x="96" y="0" text="Test2"/>

</mx:Canvas>

* test3.mxml - child3 (no problem) *
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
       horizontalScrollPolicy="off" verticalScrollPolicy="off"
       width="100%" height="100%"
       x="0" y="0">
</mx:Canvas>

* test1Child.mxml - child of child1 (no problem, but moving the bg from test1.mxml to here isnt making any difference in this test app but making diff in my originial app)
 <?xml version="1.0" encoding="utf-8"?>
 <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
       horizontalScrollPolicy="off" verticalScrollPolicy="off"
       width="{GameConfig.FULL_GAME_SCREEN_WIDTH}"
       height="{GameConfig.FULL_GAME_SCREEN_HEIGHT}"
       >
<mx:Script>
    <![CDATA[
        import com.fg.greenrev.config.GameConfig;
    ]]>
</mx:Script>
<mx:Label x="390" y="0" text="Test1Child"/>

 </mx:Canvas>

As you can see test1 and test1Child are same size and larger (huge) than the main app
child2 and child3 are 100% width and height
replace FULL_GAME_SCREEN_WIDTH and FULL_GAME_SCREEN_HEIGHT with 4096. have a dummy image of 4096x1600 and run the app you will see the bg is laid some where in the center (you can see the image if you scroll the app. now change the FULL_GAME_SCREEN_HEIGHT to 1600 (size of the bg), bg is shown perfectly.
now there are two questions
q1) how to make the bg appear in the center of the parent when bg image is smaller than the container(parent/canvas)
q2) its actually puzzle, surprisingly the bg image is appearing to almost to the right corner (at around 4000px) when it is placed in problem canvas (in my original app, test1.mxml in dummy) but appearing properly when i moved the bg to its child (test1Child in the test app)
update 3: workaround not working
I have added this as the first line in the problem canvas, bg is appearing and it is covering remaining children. I knew adding it at first lines makes it first child meaning index = 0 meaning always stays back side but surprisingly, its not just making its' children canvas invisible but also occluding the other controls which are inside the other canvas. I have also tried to dynamically add the image using addChildAt(img,0) and also forecefully made the index to 0 by setChildIndex(img,0) but no use. Sick and tired

A: working workaround
well i thought this woould work
<mx:Image x="0" y="0" source="{GameResource.bg}" mouseEnabled="false"/>

but for some reason it was occlding remaining controls and containers, despite it was added at the very first line (which makes ints displayindex = 0)
then I addeed this code to add them dynamically
            var img:Image = new Image();
            img.mouseEnabled = false;
            img.mouseChildren = false;
            img.source = GameResource.bg;

            addChildAt(img,0);

working like charm. BLOODY FLEX VERY UNPREDICTABLE


Q: Are these subsets of $\mathbb{R}$ homeomorphic? Consider the following subspaces of $\mathbb{R}$ with the usual topology:
$$X = (0, 1) \cup \{2\} \cup (3, 4) \cup \{5\} \cup \cdots \cup (3n, 3n + 1) \cup \{3n + 2\} \cup\cdots$$
$$Y = (0, 1] \cup (3, 4) \cup \{5\} \cup\cdots\cup (3n, 3n + 1) \cup \{3n + 2\} \cup\cdots$$
Is $X$ homeomorphic to $Y$ ?
For $X$ to be homeomorphic to $Y$, we need to specify a bijective function from $X$ to $Y$ and inverse function from $Y$ to $X$ are continuous. From $(3,4)$ onwards, we can map by identity function. How can I map $(0,1) \cup \{2\}$ to $Y$? $(0,1]$, in usual topology is not open and closed. Can I write $(0,1]$ as $(0,1)\cup\{1\}$, and then map $\{0,1\}$ by identity map and $\{1\}$ to $\{2\}$. Please forgive me if any of what I think is stupid.

A: Hint: If $f:A\to B$ is a continuous map between topological spaces, and $R$ is a connected component of $A$, then there is a connected component $S$ of $B$ such that $f(R)\subseteq S$.
What does this imply about how homeomorphisms map the connected components of spaces?
Do you see how to apply this to your situation?

A: Hints:

*

*If $f:X\to Y$ is a homeomorphism, then the disconnected singletons of $X$ must map to the disconnected singletons $Y$. Reason being that they are isolated points (open subsets) in $X$ and thus their images are also isolated points in $Y$.

*If $f:X\to Y$ is a homeomorphism, then the image of a connected set is connected. Hence any interval in $X$ must map to an interval in $Y$.

*Conclude with 1. & 2. that if $f:X\to Y$ is a homeomorphism, then an interval of the form $(3n,3n+1)$ is homeomorphic to $(0,1]$ for some $n\in\mathbb{N}$. Take the co-restriction of this homeomorphism to the set $(0,1)$, and try to conclude a contradiction with a connectedness argument.

A: Connectedness is a topology invariant, so $(0,1]$ and $(0,1)\cup\{2\}$ cannot be homeomorphic with the usual topology.

A: Proof 1. Suppose $f:Y\to X$ is a homeomorphism.  The image $f((0,1])$ must be an interval and an infinite set   so it must be a  subset of $(3n,3n+1)$ for some $n.$
But $(0,1]$ has a unique point (i.e., $1$) which, if removed,  leaves a connected set. Since $f((0,1])$ is a homeomorphic image of $(0,1]$ it must also have this property.
So  $f((0,1])=(a,b]$ with $3n\leq a<b<3n+1$, or  $f((0,1])=[b,a)$ with $3n<b<a\leq 3n+1,$ and with $f(1)=b$ in either case.
But in either case  we have $b=f(1)\in Cl_X(X$ \ $f((0,1])$ but $1\not \in Cl_Y(Y$ \ $(0,1]),$ which means $f $ cannot be a homeomorphism.
Proof 2.  If $D\subset \mathbb R$ and $D$ is the homeomorphic image of an open real interval $J$ then $D$ is an open real interval. ($D$ must be connected, so $D$ is an interval. And there cannot exist $d\in D$ such that $D \backslash  \{d\}$ is connected ....else $J$ would have such a point... So $D$ cannot have end-points.)
So if $S$ is an open subset of $\mathbb R$ then any subset of $\mathbb R$ which  is a homeomorphic image of $S$ must be open in  $\mathbb R.$ (Because any open real set is the union of a family of pair-wise disjoint open intervals.)
Suppose $g:X\to Y$ was a homeomorphism . Let $X^i$ and $Y^i$ be the sets of isolated points of $X,Y$ respectively. Then $g(X^i)=Y^i.$ So $g(X$ \ $X^i)=Y$ \ $Y^i .$ But $X$ \ $X^i$ is open in $\mathbb R$ and $Y$ \ $Y^i$ is NOT open in $\mathbb R,$ a contradiction.
Remark. For the sake of pedantic precision, I include sets of the form $(-\infty,r)$ and $(r,\infty)$ and $\phi$ and $\mathbb R$  among the open real intervals.


Q: How to remove tmp directory files of an ios app? I'm working on an app that uses the iPhone camera and after making several tests I've realised that it is storing all the captured videos on the tmp directory of the app.
The captures don`t disappear even if the phone is restarted.
Is there any way to remove all these captures or is there any way to easily clean all cache and temp files?

A: Yes. This method works well:
+ (void)clearTmpDirectory
{
    NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
    for (NSString *file in tmpDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
    }
}

A: Try this code to remove NSTemporaryDirectory files
-(void)deleteTempData
{
    NSString *tmpDirectory = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error];
    for (NSString *file in cacheFiles)
    {
        error = nil;
        [fileManager removeItemAtPath:[tmpDirectory stringByAppendingPathComponent:file] error:&error];
    }
}

and to check data remove or not write code in didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];

    NSString *tmpDirectory = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error];
    NSLog(@"TempFile Count ::%lu",(unsigned long)cacheFiles.count);

    return YES;
}

A: Thanks to Max Maier and Roman Barzyczak. Updated to Swift 3, using URLs instead of strings.
Swift 3
func clearTmpDir(){

        var removed: Int = 0
        do {
            let tmpDirURL = URL(string: NSTemporaryDirectory())!
            let tmpFiles = try FileManager.default.contentsOfDirectory(at: tmpDirURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
            print("\(tmpFiles.count) temporary files found")
            for url in tmpFiles {
                removed += 1
                try FileManager.default.removeItem(at: url)
            }
            print("\(removed) temporary files removed")
        } catch {
            print(error)
            print("\(removed) temporary files removed")
        }
}

A: Swift 3 version as extension:
extension FileManager {
    func clearTmpDirectory() {
        do {
            let tmpDirectory = try contentsOfDirectory(atPath: NSTemporaryDirectory())
            try tmpDirectory.forEach {[unowned self] file in
                let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
                try self.removeItem(atPath: path)
            }
        } catch {
            print(error)
        }
    }
}

Example of usage:
FileManager.default.clearTmpDirectory()

Thanks to Max Maier, Swift 2 version:
func clearTmpDirectory() {
    do {
        let tmpDirectory = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory())
        try tmpDirectory.forEach { file in
            let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
            try NSFileManager.defaultManager().removeItemAtPath(path)
        }
    } catch {
        print(error)
    }
}

A: Swift 4
One of the possible implementations
extension FileManager {
    func clearTmpDirectory() {
        do {
            let tmpDirURL = FileManager.default.temporaryDirectory
            let tmpDirectory = try contentsOfDirectory(atPath: tmpDirURL.path)
            try tmpDirectory.forEach { file in
                let fileUrl = tmpDirURL.appendingPathComponent(file)
                try removeItem(atPath: fileUrl.path)
            }
        } catch {
           //catch the error somehow
        }
    }
}

A: This works on a jailbroken iPad, but I think this should work on a non-jailbroken device also.
-(void) clearCache
{
    for(int i=0; i< 100;i++)
    {
        NSLog(@"warning CLEAR CACHE--------");
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError * error;
    NSArray * cacheFiles = [fileManager contentsOfDirectoryAtPath:NSTemporaryDirectory() error:&error];

    for(NSString * file in cacheFiles)
    {
        error=nil;
        NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:file ];
        NSLog(@"filePath to remove = %@",filePath);

        BOOL removed =[fileManager removeItemAtPath:filePath error:&error];
        if(removed ==NO)
        {
            NSLog(@"removed ==NO");
        }
        if(error)
        {
            NSLog(@"%@", [error description]);
        }
    }
}

A: I know i'm late to the party but i'd like to drop my implementation which works straight on URLs, too:
let fileManager = FileManager.default
let temporaryDirectory = fileManager.temporaryDirectory
try? fileManager
    .contentsOfDirectory(at: temporaryDirectory, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants)
    .forEach { file in
        try? fileManager.removeItem(atPath: file.path)
    }

A: //
//  FileManager+removeContentsOfTemporaryDirectory.swift
//
//  Created by _ _ on _._.202_.
//  Copyright © 202_ _ _. All rights reserved.
//

import Foundation

public extension FileManager {

    /// Perform this method on a background thread.
    /// Returns `true` if :
    ///     * all temporary folder files have been deleted.
    ///     * the temporary folder is empty.
    /// Returns `false` if :
    ///     * some temporary folder files have not been deleted.
    /// Error handling:
    ///     * Throws `contentsOfDirectory` directory access error.
    ///     * Ignores single file `removeItem` errors.
    ///
    @discardableResult
    func removeContentsOfTemporaryDirectory() throws -> Bool  {

        if Thread.isMainThread {
            let mainThreadWarningMessage = "\(#file) - \(#function) executed on main thread. Do not block the main thread."
            assertionFailure(mainThreadWarningMessage)
        }

        do {

            let tmpDirURL = FileManager.default.temporaryDirectory
            let tmpDirectoryContent = try contentsOfDirectory(atPath: tmpDirURL.path)

            guard tmpDirectoryContent.count != 0 else { return true }

            for tmpFilePath in tmpDirectoryContent {
                let trashFileURL = tmpDirURL.appendingPathComponent(tmpFilePath)
                try removeItem(atPath: trashFileURL.path)
            }

            let tmpDirectoryContentAfterDeletion = try contentsOfDirectory(atPath: tmpDirURL.path)

            return tmpDirectoryContentAfterDeletion.count == 0

        } catch let directoryAccessError {
            throw directoryAccessError
        }

    }
}


Q: is there a DB client which supports oracle editions? We are using a clever feature or oracle 11gr2 called edition-based redefinitions.
This means each stored proc and view looks different depending on the edition you set in the session.  There are multiple versions of each of these objects.
I'm trying to find a DB client (for browsing data and running SQL) which supports this properly - ie can show me visually the different editions, etc.
DBVisualizer doesn't seem to do this.  Here's an example:
my program code (which explicitly sets an edition) says:
ORA-04063: package body "MATT2.ER_BATCH_SUB_PKG" has errors
But when looking in dbvisualizer to the 'invalid objects' view, I see nothing.


Q: Convergence of fixed point iteration for Omega constant In wikipedia, it is introduced that Omega constant can be computed by fixed-point iteration solving $\Omega_n = e^{-\Omega_{n-1}}$. Yet, does it converges with any starting value $\Omega_1$?
While I was confirming that it converges to omega by actually trying it with starting point around the true $\Omega$, I found that it converges even with negatively large value such as -100. However, the fixed-point iteration is not guaranteed to converge if $|f'(x)| > 1$. At -100, it has much larger gradient than $1$ so I'm confused at which starting point, it converges and where it doesn't.

A: Consider
$$f(x)=e^{-x}-x \qquad\qquad f'(x)=-e^{-x}-1<0\qquad\qquad f''(x)=e^{-x} >0$$ $f(x)$ is continuous and its first derivatives do not change sign anywhere. So, Newton will converge to the solution for any $x_0$.
However, if we start at $x_0$ such that $f(x_0) >0$, by Darboux theorem, there will not be any overshoot of the solution during Newton iterations since $f''(x_0)>0$. For illustration, start with $x_0=-10$; you will have $20$ exact figures after $15$ iterations.

A: Set $f(x)=\exp(-x)$ and $g(x)=f(f(x))=\exp(-\exp(-x))$ $(x \in \mathbb{R})$.
Start iterating $f$ for any $x_0 \in \mathbb{R}$, that is $x_{n+1}=f(x_n)$ $(n \ge 0)$. Then $x_{n+2}=g(x_n)$ $(n \ge 0)$. Since $g$ is a contraction $(0\le g'(x) \le 1/e)$ the sequence $(x_{2n})$ is convergent. Its limit $y$, say, is the unique fixed point of $g$. Moreover $f(f(y))=y$ implies $g(f(y))=f(y)$.
Since the fixed point of $g$ is unique $f(y)=y$. Finally
$x_{2n+1}=f(x_{2n}) \to f(y)=y$ $(n \to \infty)$, so $x_n \to y$ $(n \to \infty)$.


Q: Why is my react stepper component is look like small? I've used material-UI stepper to make multi-step form inside of the Drawer content which also a material-UI Drawer. But when I use that stepper code it looks like the below picture.

So, where is the error?
And that stepper code would be like:
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepButton from '@material-ui/core/StepButton';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',

    },
    button: {
        marginRight: theme.spacing(1),
    },
    backButton: {
        marginRight: theme.spacing(1),
    },
    completed: {
        display: 'inline-block',
    },
    instructions: {
        marginTop: theme.spacing(1),
        marginBottom: theme.spacing(1),
    },
}));

function getSteps() {
    return ['Select campaign settings', 'Create an ad group', 'Create an ad'];
}

function getStepContent(step) {
    switch (step) {
        case 0:
            return 'Step 1: Select campaign settings...';
        case 1:
            return 'Step 2: What is an ad group anyways?';
        case 2:
            return 'Step 3: This is the bit I really care about!';
        default:
            return 'Unknown step';
    }
}

export default function HorizontalNonLinearAlternativeLabelStepper() {
    const classes = useStyles();
    const [activeStep, setActiveStep] = React.useState(0);
    const [completed, setCompleted] = React.useState(new Set());
    const [skipped, setSkipped] = React.useState(new Set());
    const steps = getSteps();

    const totalSteps = () => {
        return getSteps().length;
    };

    const isStepOptional = (step) => {
        return step === 1;
    };

    const handleSkip = () => {
        if (!isStepOptional(activeStep)) {
            // You probably want to guard against something like this
            // it should never occur unless someone's actively trying to break something.
            throw new Error("You can't skip a step that isn't optional.");
        }

        setActiveStep((prevActiveStep) => prevActiveStep + 1);
        setSkipped((prevSkipped) => {
            const newSkipped = new Set(prevSkipped.values());
            newSkipped.add(activeStep);
            return newSkipped;
        });
    };

    const skippedSteps = () => {
        return skipped.size;
    };

    const completedSteps = () => {
        return completed.size;
    };

    const allStepsCompleted = () => {
        return completedSteps() === totalSteps() - skippedSteps();
    };

    const isLastStep = () => {
        return activeStep === totalSteps() - 1;
    };

    const handleNext = () => {
        const newActiveStep =
            isLastStep() && !allStepsCompleted()
                ? // It's the last step, but not all steps have been completed
                // find the first step that has been completed
                steps.findIndex((step, i) => !completed.has(i))
                : activeStep + 1;

        setActiveStep(newActiveStep);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };

    const handleStep = (step) => () => {
        setActiveStep(step);
    };

    const handleComplete = () => {
        const newCompleted = new Set(completed);
        newCompleted.add(activeStep);
        setCompleted(newCompleted);

        /**
         * Sigh... it would be much nicer to replace the following if conditional with
         * `if (!this.allStepsComplete())` however state is not set when we do this,
         * thus we have to resort to not being very DRY.
         */
        if (completed.size !== totalSteps() - skippedSteps()) {
            handleNext();
        }
    };

    const handleReset = () => {
        setActiveStep(0);
        setCompleted(new Set());
        setSkipped(new Set());
    };

    const isStepSkipped = (step) => {
        return skipped.has(step);
    };

    function isStepComplete(step) {
        return completed.has(step);
    }

    return (

            <Stepper alternativeLabel nonLinear activeStep={activeStep}>
                {steps.map((label, index) => {
                    const stepProps = {};
                    const buttonProps = {};
                    if (isStepOptional(index)) {
                        buttonProps.optional = <Typography variant="caption">Optional</Typography>;
                    }
                    if (isStepSkipped(index)) {
                        stepProps.completed = false;
                    }
                    return (
                        <Step key={label} {...stepProps}>
                            <StepButton
                                onClick={handleStep(index)}
                                completed={isStepComplete(index)}
                                {...buttonProps}
                            >
                                {label}
                            </StepButton>
                        </Step>
                    );
                })}
            </Stepper>

                {allStepsCompleted() ? (

                        <Typography className={classes.instructions}>
                            All steps completed - you're finished
            </Typography>
                        <Button onClick={handleReset}>Reset</Button>

                ) : (

                            <Typography className={classes.instructions}>{getStepContent(activeStep)}</Typography>

                                <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>
                                    Back
              </Button>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={handleNext}
                                    className={classes.button}
                                >
                                    Next
              </Button>
                                {isStepOptional(activeStep) && !completed.has(activeStep) && (
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        onClick={handleSkip}
                                        className={classes.button}
                                    >
                                        Skip
                                    </Button>
                                )}

                                {activeStep !== steps.length &&
                                    (completed.has(activeStep) ? (
                                        <Typography variant="caption" className={classes.completed}>
                                            Step {activeStep + 1} already completed
                                        </Typography>
                                    ) : (
                                            <Button variant="contained" color="primary" onClick={handleComplete}>
                                                {completedSteps() === totalSteps() - 1 ? 'Finish' : 'Complete Step'}
                                            </Button>
                                        ))}

                    )}

    );
}

I just changed the width. But it doesn't work. How can I correct this error?

A: I just found out the answer to that. In useStyles (styles in my code) I added marginRight: 700, to root class. Then the stepper stretched.
const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
        marginRight: 700,
    },

Now it's look like this.


Q: Using statement, As vs = Is there a difference between using 'As' keyword and the '=' operator in vb.net?
Example:
Using aThing As New Thing()
    ...
End Using

' OR

Using aThing = New Thing()
    ...
End Using

A: There will be no effective difference if you have Option Infer On.  If you have Option Infer Off then the first snippet will always result in a variable of type Thing while the second snippet will fail to compile with Option Strict On and result in a variable of type Object with Option Strict Off.
The first code snippet is explicit in its typing of the variable so it will be the type you specify regardless of what settings you have for Option Strict and Option Infer.  The second code snippet is not explicit about the type so that type must be determined implicitly by the compiler.  With Option Infer On, the type Thing can be inferred from the initialising statement.  With Option Infer Off, the type will default to Object and late-binding must be used, which is not allowed with Option Strict On.
It's worth noting that your original question isn't really valid because it's actually not a case of using As or =.  This:
Using aThing As New Thing()

is actually just a shorthand for this:
Using aThing As Thing = New Thing()

so you're actually using = either way and the choice is just whether or not to provide an As clause.  An As clause is required with Option Strict On unless you also have Option Infer On and the type can be inferred from the initialising statement.  If there is no initialising statement or the type of that statement is different to the type you want the variable to be then an As clause is required to tell the compiler the type of the variable that it cannot infer for itself.


Q: Google Maps Storelocator with filter (attributes) i am using this tutorial:
https://developers.google.com/maps/articles/phpsqlsearch_v3?hl=de
Everything works so far, but how can i add a function to filter within the results by attributes?
Anyone here who has something for me? I can not find anything so far.
many Thanks!

A: Create a selectbox with id "cat": <select id="cat">
add the selected value of this select to searchUrl in function searchLocationsNear:
 var e = document.getElementById("cat");
 var cat = e.options[e.selectedIndex].value;

 var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() +   '&radius=' + radius;
 searchurl += '&cat=' + cat;

add your filter to the query in phpsqlsearch_genxml.php:
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers  WHERE `category`='%s' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string(empty($_GET['cat'])?'':$_GET['cat']))
  mysql_real_escape_string($radius);
$result = mysql_query($query);


Q: Compare two array's and disable a single element if the id's are equal I have two array in the state and both have id's.
if some array have the same value (In this case 8) I would like to disable all the buttons that have this equal value.
The buttons already exist, I just want to disable the ones that have the same non-unique ids.
I tried like this but i'm not getting it
var setOne = [2,6,8];
var setTwo = [3, 8, 4]

const button = () => {
var hasDuplicateValues = [...new Set(setOne)].filter(item => setTwo.includes(item));

if(hasDuplicateValues.length > 0) {
   <button disabled />
}
else {
    <button />
}
}

render(){
this.button()
}

This solution is disabling all the buttons but i want to disable the one with the same id only.
Thanks

A: It's not quite clear where in the app hierarchy that component is so I've attempted a bit of guess work. You're almost there by the looks of things. You just need to iterate over the buttons and create them.

function Button(props) {
  const { disabled, text } = props;
  return <button disabled={disabled}>{text}</button>;
}

// Buttons creates the buttons in the set
function Buttons() {

  const setOne = [2, 6, 8];
  const setTwo = [3, 8, 4];

  // Remove the duplicates from the combined sets
  const combined = [...new Set([...setOne, ...setTwo])];

  // Get your duplicate values
  const hasDuplicateValues = setOne.filter(item => setTwo.includes(item));

  // `map` over the combined buttons
  // If `hasDuplicateValues` includes the current button, disable it
  return combined.map((n) => (
    <Button
      text={n}
      disabled={hasDuplicateValues.includes(n) && 'disabled'}
    />
  ));

}

ReactDOM.render(<Buttons />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/>


Q: Websocket, object Blob, utf8 Есть websocket сервер, который отправляет сообщение в кодировке utf8, на javascript принимаю сообщение и вывожу в алерт, выводиться objetc Blob.
Как преобразовать полученные данные из utf8 в строку?


Q: Cakephp 1.3: Displaying user data in paginated comments another fairly basic question I suppose, but I feel like I'm running in circles and out of ideas, haha.
I'm trying to create a commenting system with pagination (via Ajax), which has to be able to display the name, avatar, etc. of the user that wrote a particular comment. Sounds simple enough, right?
Well, everything works fine, except so far I simply wasn't able to find a way to retrieve the corresponding users information and I couldn't find anything helpful in the docs either.
Here's my pagination code so far:
$this->paginate['Comment'] = array(
    'conditions'=>array('Entry.id'=>$id),
    'contain' => array('Entry', 'User'=>array('avatar', 'username') ),
    'limit' => 10
);
$comments = $this->paginate('Comment');
$this->set(compact('comments'));

So I've used contain to get the data of the user model, which I try to display in my view like this:
echo $comment['User']['username'];
echo $comment['User']['avatar'];

But that way, it of course displays the information of the user corresponding to $id...
However, I need to get a users info through the foreignkey user_id of the current comment. And at the moment I'm at a loss how to do that... Any help would be greatly appreciated.
Thanks in advance!

A: if I remember correctly
'contain' => array('Entry', 'User.avatar,User.username')),

should do the trick

A: Okay, I solved it...
I just had to add the proper foreignKey to my Comment model, i.e:
var $belongsTo = array(
'Entry' => array('className' => 'Entry', 'foreignKey' => 'page_id'),
'User' => array('className' => 'User', 'foreignKey' => 'user_id'),
);

Now it finally fetches the appropriate user information!


Q: How to wait for a function to finish it's execution in angularJS? I've a function named validityCheck() and it's returns valid if an user is valid and invalid if the user is invalid. I need to call this function from somewhere else and use the result in if-else condition.
Here's the function definition (This function is defined in a plain javascript library name library.js):
function validityCheck(userid, serviceid, system) {
    $(document).ready(function () {
        $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) {
            console.log(data);
            return data[0];
        });

    });
}

Now I want to do this (This code section is in my project's controller):
var validity = validityCheck($scope.userid, serviceid, 'abc');
if(validity=="VALID"){
    //do something
}else{
    //do something
}

I need to wait till I get the data. I think I need to use callback_ or something like that but I don't know how to do it.

A: Why not return promise of angularjs $http and use then in your code like this?
function validityCheck(userid, serviceid, system) {
    let params = {
        userid: userid,
        serviceid: serviceid,
        system: system
    };
    let request = {
        url: "https:*******userValidation",
        method: "GET",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        params: params
    };

    return $http(request).then((response) => {
        return response.data[0] ? response.data[0] : '';
    });
}

Usage:
validityCheck($scope.userid, serviceid, 'abc').then((validity) => {
    if (validity === "VALID") {
        //do something
    } else {
        //do something
    }
});

P.S. Don't forget to inject angularjs $http
UPDATE: Register library.js in angular
(function () {
    "use strict";

    angular
        .module("yourAngularModuleName")
        .factory("LibraryFactory", LibraryFactory);

        function LibraryFactory($http) {
            // Add your functions here...
        }

})();

UPDATE: Plain JavaScript Using The Existing Code
function validityCheck(userid, serviceid, system) {
    return new Promise((resolve, reject) => {
        $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) {
            console.log(data);
            resolve(data[0]);
        });
    });
}

Use the same code in the USAGE that I have provided.


Q: Django prefetch table that is not directly related With the following models is it possible to get Category objects and prefetch OrderLine so that it can be accessed by category.orderlines.all()?
class Category(models.Model):
    name = models.CharField(...)

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', ...)
    name = models.CharField(...)
    price = models.DecimalField(...)

class OrderLine(models.Model):
    product = models.ForeignKey(Product, related_name='orderlines', ...)

I know you can do a nested prefetch through products but I'd like to access OrderLine objects directly from a Category rather than go through Product
from django.db.models import Prefetch

categories = Category.objects.prefetch_related(Prefetch(
    'products__orderlines',
    queryset=OrderLine.objects.filter(...)
))

for category in categories:
    for product in category.products.all():
        for line in product.orderlines.all():
            ...

Desired usage:
for category in categories:
    for line in category.orderlines.all():
        ...

Update
Adding to_attr='orderlines' results in:

ValueError: to_attr=orderlines conflicts with a field on the Product model.

Changing the attribute name to_attr='lines' doesn't cause an error but the attribute isn't added to the Category objects. It prefetches Product then adds a lines attribute to each product.

A: The closest I've come to this is using an ArraySubquery. The only downside being that lines is a list of dictionaries rather than model instances.
Category.objects.annotate(
    lines=ArraySubquery(
        OrderLine.objects
        .filter(category=OuterRef('id'))
        .values(json=JSONObject(
            id='id',
            product_name='product__name',
            quantity='quantity',
        ))
    )
)


Q: Display categories and sub-categories : where to paste the code? I'm very new for magento. I hire a company to create my magento website. however, there are some features that i 'd like to improve.
For displaying categories and subcategories in cms page, i found code that some kindly shared to others. But i don't know where or which file in ftp i should paste the code.
now : the page of subcategory shows only its name on left navigator.
Expectation : the page shows both parent category and all subcategories, so the customers can link to other subcategories by clicking on side menu.
This is both for products page and other pages, for example, menu "about us" has 2 subcategories : history, our vision. when the user click subcategories "our vision", it will show "about us" , "history", and "our vision" on the left side bar.
I have captured my website as belows:
parent category page ------>
subcategory page
Thank you in advance.
Code i think it may be work. (in the fact, i would like it to appear only subcategories in current category)
<?php
$_helper = Mage::helper('catalog/category');
$categories = $_helper->getStoreCategories();

foreach ($categories as $_category) {
    $category = Mage::getModel('catalog/category')->load($_category->getId());
    $subcategories = $category->getChildrenCategories();
    ?>

<?php echo $this->htmlEscape($_category->getName()); ?>

                <?php
                foreach ($subcategories as $_subcategory) {
                    echo '
getURL() . '">' . $_subcategory->getName() . '
';
                }
                ?>

    <?php

}
?>

A: I finally fixed it. go to app/design/frontend/default/YOURTEMPLATE/catalog/navigation/leftnav.phtml
And correct the code like this.
<?php
  $redirect_url = Mage::getUrl('customer/account/');
  $current_url = Mage::helper('core/url')->getCurrentUrl();
  if( $current_url != $redirect_url):?>

<?php
//     $currentCat = Mage::registry('current_category');
     $currentCat =Mage::getModel('catalog/layer')->getCurrentCategory();
    echo '

'.$currentCat->getParentCategory()->getName().'

';

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() ){
        $loadCategory = $currentCat;
    }else{
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
    }
    $subCategories = explode(',', $loadCategory->getChildren());
    if(count($subCategories) > 1){
        echo '
';
        foreach ( $subCategories as $subCategoryId ){
            $cat = Mage::getModel('catalog/category')->load($subCategoryId);
            if($cat->getIsActive()){
                echo 'getURL().'">'.$cat->getName().'';

            }
        }
        echo '
';
      }
   ?>

<?php endif ?>


Q: IIS6 and .Net 4.5? In the past, the .NET framework has been independent from IIS versions, and have worked with IIS 6+.
Will IIS 6 be supported for .NET 4.5?

A: IIS 6 is part of Windows Server 2003 (and technically XP 64-bit).
The .NET Framework 4.5 System Requirements indicate that Server 2003, thus IIS 6, is not supported.

A: Not trying to throw the last answer off, this could be a typo on MS website, but looking for the same question, I found this.
http://msdn.microsoft.com/en-us/library/ms733890.aspx
"WCF can also be installed on Windows XP SP2, Windows Server 2003 R2, or Windows Server 2003 SP1"
and that is while I have .net 4.5 selected at the top.
I am thinking typo.. but hopeful ;)


Q: GCC ignores `-mcpu=arm7tdmi` flag and generates unsupported instruction I'm trying to compile a small program for arm7tdmi (i.e. armv4t), using the command arm-linux-gnueabi-gcc -march=armv4t -mcpu=arm7tdmi -nostartfiles -static test.c -o test on Debian (gcc version 10.2.1, Debian 10.2.1-6). However, GCC seems to ignore the cpu and arch flags, and generates instructions that are unsupported on armv4t, e.g. clz, as shown by objdump:
   104f4:       0a000071        beq     106c0 <.divsi3_skip_div0_test+0x1f0>
   104f8:       e16f2f13        clz     r2, r3
   104fc:       e16f0f11        clz     r0, r1
   10500:       e0402002        sub     r2, r0, r2
   10504:       e272201f        rsbs    r2, r2, #31

I also checked the binary using readelf, and it shows the architecture is actually armv5te:
File Attributes
  Tag_CPU_name: "5TE"
  Tag_CPU_arch: v5TE
  Tag_ARM_ISA_use: Yes
  Tag_THUMB_ISA_use: Thumb-1

May I ask what's going on here? Why is GCC ignoring the -mcpu and -march flags?
Here's the content of test.c:
#include <stdint.h>
#include <stddef.h>

void _start() {
        const size_t len = 8;
        uint8_t arr[8] = {10, 12, 8, 5, 0, 2, 3, 55};
        uint8_t *data = arr;
        uint16_t a = 1, b = 0, m = 7;

        for(int i=0; i<len; i++) {
                a = (a + data[i]) % m;
                b = (a + b) % m;
        }

        uint32_t res = (uint32_t)b << 16 | (uint32_t)a;
}

A: You also need to add '-nostdlib' or it will drag in files that have been compiled with Armv5.  The 'arm-linux' kernel does not support ARMv4 CPUs as they do not have an MMU.  You are viewing assembler from the gcc library which is compiled for Armv5.
The example label divsi3, shows that you are using division operation and this is coded in libgcc, which will link with the code.  It is brought in by your % m code.
You can code and supply your own divsi3, or get a compiler library that supports Armv4.  The libgcc.a must be generated (downgraded) to support that CPU.  Gcc's backend is capable of generating code for all members of the ARM32/Thumb family, but not support libraries (without multi-lib support).
There is no bug in the compiler.  If you look at the assembler for _start, it will not contain clz.  If the % 7 could be % 8, you can downgrade to a &7 and the divsi3 would not be needed.
You can see why here.
It is a variation on this question.  The issue is that the linker 'gnu ld' has no flag to say, reject Armv5 code.

*

*Provide divsi3 configured with Armv4.

*Provide your own divsi3 with a Division algorithm.

*Avoid the functionality (down grade to &).


Q: If lookup of account does not contain value on opportunity then showing error for lightning url hack Created custom button for url hack in lightning and added on opportunity page layout. IF opportunity lookup field Account have value then it is working but if it not there then show blank. so i have added if condition but it is throwing weird error on UI showing random id and contact your system admin.
  /lightning/o/Opportunity/new?defaultFieldValues=Name={!Opportunity.Name},
   AccountId={! IF( ISBLANK( Opportunity.AccountId ) , '', Opportunity.AccountId  ) }

A: I have tried '' it's not worked then tried null again its not worked then After so much struggle, problem is resolved. so instead of null, we have to use NULL.
  /lightning/o/Opportunity/new?defaultFieldValues=Name={!Opportunity.Name},
 AccountId={! IF( ISBLANK( Opportunity.AccountId ) , NULL, Opportunity.AccountId  ) }

A: Use URLFOR() expression in formula to pass the lookup value in the parameter only if lookup value exists using ISBLANK().  Above formula will not populate account lookup field.
Try below:
{!URLFOR('/lightning/o/Opportunity/new?defaultFieldValues=Name=' +(Opportunity.Name) + IF(ISBLANK(Opportunity.AccountId),'', ',AccountId='+Opportunity.AccountId))}

Thanks,

A: Just to add to Vinay's response, as it took me some time to edit it (And it works!)

 {!URLFOR('/lightning/o/Case/new?useRecordTypeCheck=1&defaultFieldValues=Cloned_from_Case_c='+(Case.Id) //lookup
         +',Labels_Text__c='+(Case.Labels_Text__c) //text
         +',Tier__c='+(text(Case.Tier__c)) //picklist
         +',Time_Zone__c='+(text(Case.Time_Zone__c)) //Picklist
         +',Origin='+'Support' //this one is for simple static text
         +IF(ISBLANK(Case.ContactId),'',',ContactId='+Case.ContactId) //lookup
         +IF(ISBLANK(Case.SuccessId__c),'',',Success__c='+Case.SuccessId__c) //lookup
      +IF(ISBLANK(Case.AccountId),'',',AccountId='+Case.AccountId) //lookup
    )}

A: Vinay then how to use URLENCODE if my description field has special characters within the above url you have provided. In the below url IF case lookup field Account have value then it is working but if it not there then show blank and description,subject field should also include special characters if any.
{!URLFOR('/lightning/o/Case/new?useRecordTypeCheck=1&defaultFieldValues=Subject=' +(URLENCODE(Case.Subject)) +',Description=' +(URLENCODE(Case.Description))+',ParentId='+(Case.Id)+ IF(ISBLANK(Case.AccountId),'', ',AccountId='+Case.AccountId)+ IF(ISBLANK(Case.ContactId),'', ',ContactId='+Case.ContactId))}


Q: Webrtc connection failed when microphone permission granted I'm trying to establish the webrtc connection between the browser and docker container with Janus gateway with the video room plugin.
Everything works fine when I create the RTCPeerConnection from the browser with permissions to media not set or denied.
However, I experience problems when I try to connect with Janus from the browser with media permissions already granted before the connection was created. In this case, the connection state is failed. I can see in the janus (in docker container) that the remote candidates are not present there.
I can see in the webrtc console that for all pairs, there are STUN request setnt but no responses received


Q: What fuse to use for a AC/DC buck converter I want to make this 8 channel DMX Splitter. Instead of the transformers I will use 9 AC/DC Buck Converters, 5V/3.5W. According to the explanation 1.5W is enough so that should be ok.
The description also shows a slow blow 0.1A fuse to be used. However, I checked that these are relatively expansive, so I wonder if I can use e.g. a 0.25A or 0.5A fast blow fuse. I never used a fuse before, so I'm not sure if this could cause a problem (like sometimes for resistors/capacitors it also doesn't matter much, as long as the value is high/low enough). Or is a fuse not needed anyway because a buck converter has already safety within?


Q: Where would a sortedSet go in this UML diagram? I am self guiding myself through a Python Data Structures book and came across this problem for one of the exercises regarding the chapter regarding inheritance. I am very puzzled.
The problem:
A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item. Draw a class diagram that shows where you would place a new class for sorted sets in the collection framework shown in the figure below:

I am confused on where a new class for a sorted set would go in this diagram. My gut tells me, it would be a be added as a third bag interface? For example LinkedBag, ArrayBag and a new SetBag point to bag interface and abstract bag, and SetSortedBag points to SetBag?
Is this on the right track? I find this question sorta odd.

A: Assuming that LinkedBag refers to the LinkedList data structure, then yes you are correct in that Set would be a third section, with SortedSet inheriting from it. However, I would not define it as an "interface".
Interfaces are a type of class which is generally used as a blueprint for inheriting classes to follow, and does not implement their own class functions. Instead, they declare functions which their derivative classes will implement. For additional information, Abstract Classes are similar, except that they can implement their class functions. Neither Interfaces nor Abstract classes can (usually) be initialized as an object. This becomes a lot more blurry in Python which uses the general "Python Abstract Base Classes" and doesn't do Interfaces directly, but can be mocked through the abstract classes. However, as a term for general programming, the distinctions between normal classes, interfaces, and abstract classes can be important, especially since interfaces and abstract classes (usually) are not/ can not be initialized as objects. The exact rules of inheritance regarding Interfaces and Abstract Classes can differ between languages, for example in Java you can't inherit from more than one abstract class, so I won't directly address it here.
Since a Set is a data structure on its own that can, and usually should, have functionality separate from a sorted set, you would not make the set an interface, but rather a normal class. You can still inherit from normal classes, which is what you would do with SortedSet inheriting from Set.

A: A sorted set according to the narrative is a set, but with some variations in some behavior:

A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item.

This means that SortedSet would inherit from Set, just like SortedArrayBag inherits from ArrayBag. Inheritance should by the way shown in UML with a big hollow array head (small arrows like in your diagram mean a navigable association, which has nothing to do with inheritance).
A set is however not a bag.  A set contains an item at maximum once, whereas a bag may contain multiple times the same item.  This could lead to a completely different interface (e.g. membership on an item is a boolean for a set, whereas it could  be an integer for a bag).  The safe approach would therefore be to insert an AbstractSet inheriting from AbstractCollection:

A shortcut could be to deal with the set like a bag, and return a count of 1 for any item belonging to the set, ignoring multiple inserts. This would not be compliant with the Liskov Substitution Principle, since it would not respect all the invariants and weaken post-conditions.
But if you'd nevertheless go this way, you should insert Set as extending AbstractBag, and SortedSet as a specialization of Set.  In this case, your set (and sorted set) would also realise the BagInterface (even if it'd twist it). Shorn's answer analyses this situation very well.


Q: How to update WSL? I first installed WSL manually, but want to use a feature to access linux filesystems, and seems it will only work with Insiders.
So I registered my account, went to "Windows Insiders Program" setting and then "Windows Update" section, updated everything and etc
But I don't know how to update wsl to include this new feature.
It still says --mount is an invalid option

A: I was on the wrong Insider Channel. On "Beta" the feature wasn't available. Switched to "Dev", updated and restarted again. All working. Thanks a lot.


Q: shell-write command problem - How to add a "key" to a plist file via terminal? (iphone,mobileterminal) I wanted to run this command in mobileterminal (iphone):
write "/myPlist.plist" TestKey "TestStringForKey"

but it says: 'write' command not found
The plist EXISTS!
What am I doing wrong?
Is there any other way?
EDIT: TestKey does not exist in the plist. I want to create it.
EDIT: Some infos: iPod Touch with iOS 4.2.1 and with the newest mobileterminal from googlecode.
EDIT: Now I installed "write".
If I run the command i get this: usage: write user [tty]

A: I think you want the defaults command:
defaults write "myPlist.plist" TestKey "TestStringForKey"

A: I use this to write to a plist file with iPhone terminal. Just make sure you have ericautilities installed from Cydia.
plutil -key ShowedAlert -value nope /dir/ect/ory/to/playlist.plist

A: /myPlist.plist means, that myPlist.plist is in your root directory. I think, it's in your current working directory, so just use
write "myPlist.plist" TestKey "TestStringForKey"


Q: Must I declare own wxFrame class? I'm creating simple c++ application with user interface. I have written own classes with needed mechanics, and now I must display some of its components using wxWidgets. MyApp contains objects of that classes, but they are also needed in MyFrame when handling events. It would be much more comfortable without passing pointers to that objects to MyFrame and implement everything in MyApp::OnInit function. Is that possible?
// should contain informations about game state, players, gameboard, etc
class MyApp : public wxApp {
    GameBoard gb;
    Player player;
    bool lightTheme;
public:
    virtual bool OnInit();
};

// should contain only window layout, button events, etc
class MyFrame : public wxFrame {
    GameBoard *gb;
    Player *player;
    bool *lightTheme;

    std::vector<wxStaticBitmap*> cardImages;
// some events here
    void displayImages(wxGridSizer*);
public:
    MyFrame(GameBoard*, Player*, bool*);
};

A: To answer your title question, you don't have to declare MyFrame and can just create and directly use wxFrame and use Bind() to connect the different event handlers. In all but the simplest situations, it's typically convenient to have a MyFrame class centralizing the data and event handlers for the window, but it is not required by any means.
If you decide to keep everything in MyApp instead, you may find wxGetApp() useful for accessing it from various places in your code.


Q: "Shadowbox is not defined" error which suggests that Shadowbox.init(shadowbox_conf)? I am having a problem where i am getting the error "Shadowbox is not defined" and it suggests that Shadowbox.init(shadowbox_conf) is the problem.
I believe that this issue started occurring when I updated from wordpress 3.3.0 to 3.3.1.
I can't figure out why this has suddenly started to cause a problem. Unfortunately my javascript skills are lacking, so any help you could give me would be appreciated.
You can view the page in question here. (note I am using shadowbox JS plugin to use the shadowbox lightbox, and I have also integrated this with the javascript plugin isotope, which is use for layout and filtering.
http://www.imageworkshop.com/portfolio/

A: okay, i eventually tracked down the fix.
I am using the Shadowbox JS plugin. Turns out that this plugin has been removed from the repository at wordpress, and i had missed out on the latest update which fixed the compatibility issues. Follow the link below to find out more and download teh latest version if you require.
http://sivel.net/2011/12/shadowbox-js-plugin-pulled-from-the-wordpress-org-repository/


Q: Can I filter data returned by the BigQuery connector for Spark? I have adapted the instructions at Use the BigQuery connector with Spark to extract data from a private BigQuery object using PySpark. I am running the code on Dataproc. The object in question is a view that has a cardinality >500million rows. When I issue this statement:
table_data = spark.sparkContext.newAPIHadoopRDD(
    'com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'com.google.gson.JsonObject',
    conf=conf)

in the job output I see:
Bigquery connector version 0.10.7-hadoop2
Creating BigQuery from default credential.
Creating BigQuery from given credential.
Using working path: 'gs://dataproc-9e5dc592-1a35-42e6-9dd6-5f9dd9c8df87-europe-west1/hadoop/tmp/bigquery/pyspark_input20181108091647'
Estimated number of shards < desired num maps (0 < 93); clipping to 0.
Computed '2' shards for sharded BigQuery export.
Table 'projectname:datasetname.viewname' to be exported has 0 rows and 0 bytes
Estimated number of shards < desired num maps (0 < 93); clipping to 0.
Computed '2' shards for sharded BigQuery export.
Table 'projectname:datasetname.viewname' to be exported has 0 rows and 0 bytes

(timestamp/message-level/namespace removed for readability)
That was over 2 hours ago and the job is still running, there has been no more output in that time. I have looked in the mentioned gs location and can see that a directory called shard-0 has been located, but it is empty. Essentially there has been no visible activity for the past 2 hours.
I'm worried that the bq connector is trying to extract the entirety of that view. Is there a way that I can issue a query to define what data to extract as opposed to extracting the entire view?

UPDATE
I was intrigued by this message in the output:
Estimated number of shards < desired num maps (0 < 93); clipping to 0

It seems strange to me that estimated number of shards would be 0. I've taken a look at some of the code (ShardedExportToCloudStorage.java) that is getting executed here and the above message is logged from computeNumShards(). Given numShards=0 I'm assuming that numTableBytes=0 which means function call:
tableToExport.getNumBytes();

(ShardedExportToCloudStorage.java#L97)
is returning 0 and I assume that the reason for that is that the object I am accessing is a view, not a table. Am I onto something here or am I on a wild goose chase?

UPDATE 2...
To test out my theory (above) that the source object being a view is causing a problem I have done the following:
Created a table in the same project as my dataproc cluster
create table jt_test.jttable1 (col1 string)

Inserted data into it
insert into jt_test.jttable1 (col1) values ('foo')

Submitted a dataproc job to read the table and output the number of rows
Here's the code:
conf = {
    # Input Parameters.
     'mapred.bq.project.id': project
    ,'mapred.bq.gcs.bucket': bucket
    ,'mapred.bq.temp.gcs.path': input_directory
    ,'mapred.bq.input.project.id': 'myproject'
    ,'mapred.bq.input.dataset.id': 'jt_test'
    ,'mapred.bq.input.table.id': jttable1
}
table_data = spark.sparkContext.newAPIHadoopRDD(
    'com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'com.google.gson.JsonObject',
    conf=conf)
print ('got table_data')
print (table_data.toDF().head(10))
print ('row tally={}'.format(table_data.toDF().count()))

When I run the dataproc pyspark job, here's the output:
8/11/08 14:59:26 INFO <cut> Table 'myproject:jt_test.jttable1' to be exported has 1 rows and5 bytes
got table_data
[Row(_1=0, _2=u'{"col1":"foo"}')]
row tally=1

Create a view over the table
create view jt_test.v_jtview1 as select col1 from `myproject.jt_test.jttable1`

Run the same job but this time consume the view instead of the table
conf = {
    # Input Parameters.
     'mapred.bq.project.id': project
    ,'mapred.bq.gcs.bucket': bucket
    ,'mapred.bq.temp.gcs.path': input_directory
    ,'mapred.bq.input.project.id': 'myproject'
    ,'mapred.bq.input.dataset.id': 'jt_test'
    ,'mapred.bq.input.table.id': v_jtview1
}

When I run the dataproc pyspark job, here's the output:
Table 'dh-data-dev-53702:jt_test.v_jtview1' to be exported has 0 rows and 0 bytes

and that's it! There's no more output and the job is still running, exactly the same as I explained above. Its effectively hung.
Seems to be a limitation of the BigQuery connector - I can't use it to consume from views.

A: To close the loop here, jamiet@ confirmed in the comment that root cause is that BigQuery does not support export from Views, it supports export only from Tables.


Q: CSS Box-model seems to be broken in Chrome 15 (latest stable release) I thought the days of checking box-model issues between modern browsers were long gone...
I have been having problems getting Chrom[e|ium] to display my website correctly, and I've managed to create this really simple example of what's going wrong:
The HTML:

LEFT!

        RIGHT! 16px margins on everything.... What's that??? → → →

The CSS:
div.left {
    float: left;
    margin: 16px;
    padding: 16px;
    width: 256px;
    height: 256px;
    outline: 1px solid red;
    background: #fee;
}

div.right {
    margin: 16px;
    padding: 16px;
    overflow: hidden;
    outline: 1px solid blue;
        background: #eef;
}

A screenshot of the problem:

A live demo:
http://jsfiddle.net/g105b/BJuYR/

A: No other browser behaves like WebKit does here.
Searching WebKit Bugzilla for "block formatting context margin" yields this very similar result:
https://bugs.webkit.org/show_bug.cgi?id=19123
As a workaround, you can use the fix I proposed in a comment:

removing the left margin on div.right sorts it out:
  http://jsfiddle.net/BJuYR/13/


Q: How to retry Django Celery task on Exception when Internal Server Error is raised? I am trying to use Celery to send anywhere from 1 to about 25 consecutive requests to a third-party API. The measure of success is whether I get a URL back in the response payload: response_json["data"]["url"]. Celery or not, sometimes I get the data I expect, and sometimes I don't.
I decided to experiment with Celery to retry the API call while taking advantage of the built-in exponential backoff, which sounds perfectly suited to my needs, but I am struggling to implement.
When the data I am expecting is not available in the response payload, I get a TypeError: 'type' object is not iterable (i.e., there is no such item in the response). But I am also getting an Internal Server Error, which I wonder whether I need to handle or whether I could use to trigger the retry.
Here is a example of one of several similar approaches I have tried:
@shared_task(autoretry_for=(Exception), retry_backoff=True, retry_backoff_max=120)
def third_party_api_request(payload, api_url, headers):
    response = requests.request("POST", api_url, headers=headers, data=payload)
    response_json = response.json()
    return response_json["data"]["url"]

# output:
Internal Server Error:
-- snip --
    autoretry_for = tuple(
TypeError: 'type' object is not iterable

Another approach I have tried:
@shared_task(bind=True)
def third_party_api_request(self, payload, api_url, headers):
    try:
        response = requests.request("POST", api_url, headers=headers, data=payload)
        response_json = response.json()
        return response_json["data"]["url"]
    except TypeError as exc:
        logger.error("Error sending request to API: %s", exc)
        raise self.retry(exc=exc)

# output:
ERROR 2022-04-22 17:31:40,131 tasks 72780 123145528369152 Error sending request to API: 'NoneType' object is not subscriptable
Internal Server Error:
-- snip --
TypeError: 'NoneType' object is not subscriptable
-- snip --
    raise ret
celery.exceptions.Retry: Retry in 180s: TypeError("'NoneType' object is not subscriptable")
ERROR 2022-04-22 17:31:40,409 log 72780 123145528369152 Internal Server Error:
-- snip --
TypeError: 'NoneType' object is not subscriptable
-- snip --
   raise ret
celery.exceptions.Retry: Retry in 180s: TypeError("'NoneType' object is not subscriptable")

And yet another approach, with similar results:
@shared_task(autoretry_for=(TypeError), retry_backoff=True, retry_backoff_max=120)
def send_http_request_to_proctoru_task(payload, api_url, headers):
    response = requests.request("POST", api_url, headers=headers, data=payload)
    response_json = response.json()
    try:
        return response_json["data"]["url"]
    except TypeError:
        logger.error("API response: %s", response_json)
        raise

A: The issue was I had misplaced the return statement. I still have much fine-tuning to do, but the following code solves the issue in the question that I posed earlier today. I have been reading posts, documentation, and articles for days, and I wish I could everyone credit, but this is the blog post that ultimately helped me realize my error: https://testdriven.io/blog/retrying-failed-celery-tasks/.
@shared_task(name="send_http_request_to_proctoru_task", bind=True, max_retries=6)
def send_http_request_to_proctoru_task(self, api_url, headers, payload):
    try:
        response = requests.request("POST", api_url, headers=headers, data=payload)
        response_json = response.json()
        if response_json["response_code"] == 2:
            raise Exception()

        return response_json["data"]["url"]
    except Exception as exc:
        logger.warning("Exception raised. Executing retry %s" % self.request.retries)
        raise self.retry(exc=exc, countdown=2 ** self.request.retries)


Q: Use only one Junction Table per Database? I am currently working on a Database-Design for an insurer. Example-Entities are "Customer", "Address", "Vehicle", "Building" etc..
So there are many Relations and every Relation has some Context. e.g. Customer-Vehicle: Customer can be owner, driver, lessee of a vehicle...
Basically I see two options on how to handle that:
(1): A Junction Table for every relation, with the two foreign keys and a context-ID. This would lead to many junction tables, with partially very few data in it. Selects would be a little bit difficult, because of the amount of tables.
(2): One Junction Table for the whole Database. This table would contain two foreign keys, one key as to what relation it is (e.g. customer-vehicle) and a key for the context. This would lead to a huge junction table, but also simpler selects.
Which one is the better solution? Are there any main advantages/disadvantages or even other solutions I didn't think of?
Thank you for your help. If I didn't express myself clear enough or something is not understandable, please ask. (English is not my native language)

A: The first solution is the best.

*

*The second solution will give you less tables but in case that you need to join 3 tables with 2 junctions you need to use the big junction table twice in your SQL.

*In case that you want to create constraints between a table and it's junction (is practically mandatory) then this is not possible in the second solution. Your data integrity will not be checked by the database.

*The ER diagram for the second solution will look complicated for somebody that needs to get data out of your database.


Q: Syntax Issue while Declaring select statement into a variable If I run the select statement its working fine but if I defined into a variable then I am getting syntax error.
Declare @a varchar(2550)

SET @a='
        SELECT 'ALTER DATABASE ' + CAST(DB_NAME() AS VARCHAR(50)) + ' MODIFY FILE ( NAME = ' +
 QUOTENAME( df.name,'''') + ', NEWNAME = ''' +
QUOTENAME( DB_NAME())    +
+ CASE
  WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )'
  WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )'
  WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )'
 END
FROM sys.database_files df'

 select @a

Error:

Msg 102, Level 15, State 1, Line 38 Incorrect syntax near ' +
CAST(DB_NAME() AS VARCHAR(50)) + '.

A: It's a combination of typing errors and wrong use of SET and/or SELECT. If I understand you correctly, you may try to use the following statement:
DECLARE @a varchar(2550)

SELECT @a =
   'ALTER DATABASE ' +
   CAST(DB_NAME() AS VARCHAR(50)) +
   ' MODIFY FILE ( NAME = ' +
   QUOTENAME( df.name,'''') + ', NEWNAME = ''' +
   QUOTENAME( DB_NAME()) +
   CASE
     WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )'
     WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )'
     WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )'
  END
FROM sys.database_files df

SELECT @a

As an important note, when you use SELECT @local_variable and the SELECT statement returns more than one value, the variable is assigned the last value that is returned. So if you want to generate a complex statement for all database files, you need to concatenate the returned rows (using FOR XML PATH or STRING_AGG()). In this case, as @GordonLinoff commented, you may declare the @a variable as nvarchar(max):
DECLARE @a nvarchar(max) = N''

SELECT @a = (
   SELECT
      N'ALTER DATABASE ' +
      CAST(DB_NAME() AS VARCHAR(50)) +
      N' MODIFY FILE ( NAME = ' +
      QUOTENAME( df.name,'''') +
      N', NEWNAME = ''' +
      QUOTENAME( DB_NAME()) +
      CASE
        WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN N'.mdf'' )'
        WHEN df.type_desc = 'LOG' THEN N'_log.ldf'' )'
        WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN N'.ndf'' )'
      END +
      N';'
   FROM sys.database_files df
   FOR XML PATH('')
)

SELECT @a

A: I think you're looking for something like this
declare @a nvarchar(max);

with file_cte as (
    select
      N'ALTER DATABASE ' + quotename(db_name()) +
      N' MODIFY FILE ( NAME = ' + quotename( df.name,'''') +
      N', NEWNAME = ''' + quotename(db_name()) +
        case when df.type_desc = N'ROWS' AND df.file_id = 1 then N'.mdf'' )'
             when df.type_desc = N'LOG' THEN N'_log.ldf'' )'
             when df.type_desc = N'ROWS' AND df.file_id != 1 then N'.ndf'' )' end string
    from sys.database_files df)
select @a=concat(string_agg(string, ';'), ';')
from file_cte;

select @a;


Q: Access to Cosmos db emulator on local machine from Linux docker I little confused with Linux docker and cosmos db emulator. I have an emulator installed on my local machine. On my Windows 10 I have a Linux docker container with Web API ASP.NET core application. When I try to get access from container to cosmos db I get an exception -> HttpRequestException: Connection refused. In C# code I get needed options like AuthKey and Uri to database from environment variables. Looks like I have an issue with network between container and localhost but I can not understand how I can connect these. Below provided docker-compose.yml and docker-compose.override.yml files.
event.webapi:
    container_name: event.webapi
    image: '${DOCKER_REGISTRY-}eventwebapi'
    environment:
     **- AzureCollectionName=Events
     - AzureDatabaseName=EventsDatabase**
    build:
      context: .
      dockerfile: src/Services/Event/Event.WebApi/Dockerfile

````````````````` docker-compose.override.yml
event.webapi:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:443;http://+:80
      - ASPNETCORE_HTTPS_PORT=44378
      **- AzureEndpointUri=https://127.0.0.1:8081
      -AzurePrimaryKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==**
    ports:
      - "53753:80"
      - "44378:443"
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

A: You need to add https://host.docker.internal:8081/ as the endpoint to cosmosdb emulator.


Q: How to dynamically hide/show widgets? I want to dynamically hide/show widget like so:
Default:
|-------|
|       |
| text  |
| editor|
|-------|

With webkit preview:
|-------|-------|
|       |       |
| text  | web   |
| editor| widget|
|-------|-------|

With okular preview:
|-------|-------|
|       |       |
| text  | okular|
| editor| widget|
|-------|-------|

A: Just add all your widgets into the layout and use QWidget::hide(), QWidget::show() when needed.
For more complex situations you can use The State Machine Framework.


Q: Summarize the data using two Python data Frames I have two data frames. I would like to do some analysis by using these two tables. I thought of using Joins but it didn't work. Hence reaching out for help. Let me elaborate the problem with the help of data. This data is not complete data, just for understanding purpose I have created these sample data. In reality, the data sizes are big.
I have two inputs tables.
Table1:

Month
Area
State_Code
State_Name

Jan
101
TX01
Total_Country

Feb
101
TX01
Total_Country

Feb
101
TX04
South

Jan
102
TX01
Total_Country

Feb
102
TX01
Total_Country

Feb
102
TX06
North

Feb
102
TX12
Mumbai

The point to be noted here is Area "101" is mapped to State_Name "Total_Country" twice because we have two Month - Jan and Feb. But Area "101" is mapped to State_Name "South" only once because it is active only from Month "Feb".
Table2:

Month
Area
Brand
Price
Sales

Jan
101
Nestle
14
300

Jan
101
Unilever
15
380

Feb
101
Abc
10
320

Feb
101
Nestle
14
420

Feb
101
Unilever
15
500

Jan
102
Nestle
15
310

Jan
102
Unilever
16
390

Feb
102
Nestle
15
430

Feb
102
Unilever
16
510

This is the brand level data for every month in an individual area.
Output Table:
The output must contain Sum of(Price) and Sum of(Sales) at Month * State_Code * State_Name * Brand.

Month
State_Code
State_Name
Brand
Price
Sales

Jan
TX01
Total_Country
Nestle
29
610

Jan
TX01
Total_Country
Unilever
31
770

Feb
TX01
Total_Country
Abc
10
320

Feb
TX01
Total_Country
Nestle
29
850

Feb
TX01
Total_Country
Unilever
31
1010

Feb
TX04
South
Abc
10
320

Feb
TX04
South
Nestle
14
420

Feb
TX04
South
Unilever
15
500

Feb
TX06
North
Nestle
15
430

Feb
TX06
North
Unilever
16
510

Feb
TX12
Mumbai
Nestle
15
430

Feb
TX12
Mumbai
Unilever
16
510

Thanks in advance for help..!

A: Try merge then create the summary values via groupby sum:
new_df = (
    df1.merge(df2)
        .drop('Area', 1)
        .groupby(['Month', 'State_Code', 'State_Name', 'Brand'],
                 as_index=False, sort=False)
        .sum()
)

new_df:
   Month State_Code     State_Name     Brand  Price  Sales
0    Jan       TX01  Total_Country    Nestle     29    610
1    Jan       TX01  Total_Country  Unilever     31    770
2    Feb       TX01  Total_Country       Abc     10    320
3    Feb       TX01  Total_Country    Nestle     29    850
4    Feb       TX01  Total_Country  Unilever     31   1010
5    Feb       TX04          South       Abc     10    320
6    Feb       TX04          South    Nestle     14    420
7    Feb       TX04          South  Unilever     15    500
8    Feb       TX06          North    Nestle     15    430
9    Feb       TX06          North  Unilever     16    510
10   Feb       TX12         Mumbai    Nestle     15    430
11   Feb       TX12         Mumbai  Unilever     16    510

A: You can do a pd.merge() with multiple columns, so that it is a dual-key merge/join.
edit: you will also need to drop() the 'area' column
df3 = pd.merge(df1,df2,on=['Month','Area']).drop('Area',axis=1)
output = df3.groupby(['Month','State_Code','State_Name','Brand'],as_index=False,sort=False).sum()

df3
    Month   Area    State_Code  State_Name  Brand   Price   Sales
0   Jan 101 TX01    Total_Country   Nestle  14  300
1   Jan 101 TX01    Total_Country   Unilever    15  380
2   Feb 101 TX01    Total_Country   Abc 10  320
3   Feb 101 TX01    Total_Country   Nestle  14  420
4   Feb 101 TX01    Total_Country   Unilever    15  500
5   Feb 101 TX04    South   Abc 10  320
6   Feb 101 TX04    South   Nestle  14  420
7   Feb 101 TX04    South   Unilever    15  500
8   Jan 102 TX01    Total_Country   Nestle  15  310
9   Jan 102 TX01    Total_Country   Unilever    16  390
10  Feb 102 TX01    Total_Country   Nestle  15  430
11  Feb 102 TX01    Total_Country   Unilever    16  510
12  Feb 102 TX06    North   Nestle  15  430
13  Feb 102 TX06    North   Unilever    16  510
14  Feb 102 TX12    Mumbai  Nestle  15  430
15  Feb 102 TX12    Mumbai  Unilever    16  510

output

Month   State_Code  State_Name  Brand   Area    Price   Sales
0   Jan TX01    Total_Country   Nestle  203 29  610
1   Jan TX01    Total_Country   Unilever    203 31  770
2   Feb TX01    Total_Country   Abc 101 10  320
3   Feb TX01    Total_Country   Nestle  203 29  850
4   Feb TX01    Total_Country   Unilever    203 31  1010
5   Feb TX04    South   Abc 101 10  320
6   Feb TX04    South   Nestle  101 14  420
7   Feb TX04    South   Unilever    101 15  500
8   Feb TX06    North   Nestle  102 15  430
9   Feb TX06    North   Unilever    102 16  510
10  Feb TX12    Mumbai  Nestle  102 15  430
11  Feb TX12    Mumbai  Unilever    102 16  510


Q: Sort Multi-dimensional array by value dynamically with PHP This Stackoverflow answer is 95% of the way there: https://stackoverflow.com/a/10484863.  I just need to pass another variable into the function which I believe uses closure.
I want to pass the variable sort:
$sort = get_category_name();

into:
function compareByName($a, $b) {
  return strcmp($a["name"], $b["name"]);
}

usort($a, 'compareByName');

so its $a[$sort] and not defined by me as $a[key].
My array:
Array(
[0] => Array
    (
        [id] => 7
        [product_type_id] => 2
        [category_en] => Prints
        [category_es] => Impresiones
        [category_ru] => Печати
    )

[1] => Array
    (
        [id] => 8
        [product_type_id] => 2
        [category_en] => Drawings
        [category_es] => Dibujos
        [category_ru] => Рисунки
    )

[2] => Array
    (
        [id] => 9
        [product_type_id] => 2
        [category_en] => Paintings
        [category_es] => Pinturas/Cuadros
        [category_ru] => Картины
    )
)

should allow me to sort the array by the category based on the users language which is set by get_category_name().


Q: Unexpected search results when querying for files based on mimeType - Google Drive API v3 + Javascript I am trying to search Google Drive for Excel files using the Javascript API (v3). Some Excel files seem to have a mime type of 'application/vnd.ms-excel' and some have a mime type of 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'.
When I use mime type 'application/vnd.ms-excel', the files with that mime type are returned correctly. But, when I use the mime type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' I get a ton of irrelevant results (with mime types like 'x-javascript', 'x-markdown', and even 'image/png').
Is this a bug or am I doing something wrong?
Any help will be greatly appreciated! Thanks.
Here's my code:
function getItemsByQuery(query, callback) {

    var retrievePageOfFiles = function(request, result) {
        request.execute(function(resp) {
            result = result.concat(resp.files);
            var nextPageToken = resp.nextPageToken;
            if (nextPageToken) {
                request = gapi.client.drive.files.list({ 'pageToken': nextPageToken });
                retrievePageOfFiles(request, result);
            }
            else {
                result.length > 0 ? callback(result) : callback([]);
            }
        });
    };

    var q = {'q': query };
    var initialRequest = gapi.client.drive.files.list(q);
    retrievePageOfFiles(initialRequest, []);
}

getItemsByQuery("trashed=false and mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'", function(results) {
    // Handle results - lots of irrelevant files returned here.
});

A: It looks like you forgot to add the q field when rebuilding the query with a pageToken field.


Q: JavaScript primitives: same memory location, new memory location, or engine-dependent? 10    var x = 5;
11    x = 10;

Does the memory location of the variable x change in line 11 from line 10 OR does the JavaScript engine just overwrites the memory space originally allocated to x in line 10 and place the value 10 there? Is this specified, or engine-dependent?

A: According to Javascript documentation, assigning values means reading and writing to memory that is already allocated.
When you assign a variable, memory is allocated. When you change its value, reading and writing is done on the same memory location.


Q: Error Mysqli fetch array PHP MYSQL Estoy intentando conectar con php mysql,me dieron un código antiguo,usa el mysql clásico entonces quise usar mysqli pero me sale un error en

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given"

vi otros foto pero no se ajusta a nada,quisiera saber el porque me sale error
function consultaUsuarios($conexion){
$conex= new mysqli('localhost','root','root','call_center');
$salida='';
//Realizamos la Consulta que nos traera todos los registros de la BD
$query="select id,marca,producto,nombre,area
 from creacion";
$total=mysqli_query($conex,$query);
$consulta=$conex->query($query);
 //Validamos si hay o no registros
 if(!$total || mysqli_num_rows($total) == 0){
     while($dato=mysqli_fetch_array($total)){
         $salida.='

                '.$dato["id"].'
                '.$dato["marca"].'
                '.$dato["producto"].'
                '.$dato["nombre"].'
                '.$dato["area"].'
                '.$dato["status"].'
                Editar

         ';
     }
 }
 else
 {
     $salida='

            No hay Registros en la Base de Datos, Tu codigo!!

     ';
 }

La conexión la pongo dentro solo para practicar algo rápido

A: Tiene inconsistencias tu código. ¿En dónde utilizas $consulta? Estas haciendo un query que no estas usando. Segundo. La lógica de validación si la consulta trajo datos o no está mal hecha.
function consultaUsuarios(){//ELIMINA EL PARAMETRO DE CONEXIÓN POR QUE NO LA ESTÁS USANDO, YA TIENES UNA DENTRO
$conex= mysqli_connect('localhost','root','root','call_center'); //CORREGI TU CONEXIÓN A MYSQLI
$salida='';
//Realizamos la Consulta que nos traera todos los registros de la BD
$query="select id,marca,producto,nombre,area
 from creacion";
$total=mysqli_query($conex,$query);
//QUITAMOS LA CONSULTA DE MYSQL Y NOS QUEDAMOS CON MYSQLI
 //Validamos si hay o no registros
 if($total && mysqli_num_rows($total) < 0){//LA LOGICA ESTA MAL, AHÍ ESTÁ CORREGIDA
     while($dato=mysqli_fetch_array($total)){
         $salida.='

                '.$dato["id"].'
                '.$dato["marca"].'
                '.$dato["producto"].'
                '.$dato["nombre"].'
                '.$dato["area"].'
                '.$dato["status"].'
                Editar

         ';
     }
 }
 else
 {//SE TE BARRIÓ PONER EL PUNTO PARA CONCATENAR LA SALIDA
     $salida.='

            No hay Registros en la Base de Datos, Tu codigo!!

     ';
 }
echo $salida; //MUESTRALA

A: Estas duplicando la consulta:
//$total=mysqli_query($conex,$query); consulta 1

$consulta=$conex->query($query);     nuevamente consulta

luego tu validación esta expresada erroneamente:
if(!$total || mysqli_num_rows($total) == 0)
indicas que tu consulta tiene que ser falso y no debe de tener registros tu consulta, debes de cambiar tu condición.
if(mysqli_num_rows($consulta) > 0)

luego al querer recorrer tu consulta igual esta expresada erroneamente:
while($dato=mysqli_fetch_array($total))

al hacer eso nunca recorrera los valores corrigeme si me equivoco.
te recomendari hacer lo siguiente:
    $array = mysqli_fetch_all($consulta); // almacenar todos tus registros dentro de un variable de tipo array

        foreach ($array as $item) // recorrer registro por registro
        {
           // imprimir los valores aqui
            echo '
';// lo que hago a partir de aqui es opcional, solo si quieres personalizar tus columnas
            foreach ($item as $do)//recorres las columnas del registro
            {
                echo ''.$do.'	';//imprimes la columna
            }
            echo '
';
        }


Q: PETSc C macro within struct In PETSc, a number of common-use structures such as Vec, Mat, IS, etc. are defined similarly, as in the 4 snippets below.
Questions:

*

*when and how is PETSCHEADER expanded? I am writing the foreign interface from another language, and was wondering whether I have to wrap the macro in a function or whatnot

*What's the scope of hdr and ops ?

Thanks in advance

petscvec.h
typedef struct _p_Vec* Vec;

vecimpl.h
struct _p_Vec {
  PETSCHEADER(struct _VecOps);
  PetscLayout            map;
  void                   *data;     /* implementation-specific data */
  ...

petscimpl.h
#define PETSCHEADER(ObjectOps) \
  _p_PetscObject hdr;          \
  ObjectOps      *ops

vecimpl.h
typedef struct _VecOps *VecOps;
struct _VecOps {
  PetscErrorCode (*duplicate)(Vec,Vec*);         /* get single vector */
  PetscErrorCode (*duplicatevecs)(Vec,PetscInt,Vec**);     /* get array of vectors */
...